package com.recipedb.sprint.repository;

import com.recipedb.sprint.entity.PointsRewards;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface PointsRewardsRepository extends JpaRepository<PointsRewards, Long> {
    Optional<PointsRewards> findByUserid(Long userid);

    boolean existsByUserid(Long userid);

    @Modifying
    @Query("update PointsRewards p set p.points = p.points + ?2, p.updatedAt = CURRENT_TIMESTAMP where p.userid = ?1")
    int addPoints(Long userid, Integer points);

    @Modifying
    @Query("update PointsRewards p set p.points = p.points - ?2, p.updatedAt = CURRENT_TIMESTAMP where p.userid = ?1 and p.points >= ?2")
    int deductPoints(Long userid, Integer points);
}
